package com.zjsystem.zjsy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zjsystem.zjsy.dto.*;
import com.zjsystem.zjsy.enums.AuditEnums;
import com.zjsystem.zjsy.enums.PlanDwEnums;
import com.zjsystem.zjsy.enums.SubStatusEnums;
import com.zjsystem.zjsy.mapper.ZjxdPlanMapper;
import com.zjsystem.zjsy.request.PlanRequest;
import com.zjsystem.zjsy.request.StageInfoRequest;
import com.zjsystem.zjsy.response.InstructPreviewRsp;
import com.zjsystem.zjsy.response.PlanSchemeResponse;
import com.zjsystem.zjsy.response.SchemeResponse;
import com.zjsystem.zjsy.result.Result;
import com.zjsystem.zjsy.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 筹划任务监控表 服务实现类
 * </p>
 *
 * @author wyf
 * @since 2024-07-11
 */
@Slf4j
@Service
public class ZjxdPlanServiceImpl extends ServiceImpl<ZjxdPlanMapper, ZjxdPlan> implements ZjxdPlanService {

    @Resource
    private ZjxdAssignmentService assignmentService;
    @Resource
    private ZjxdPlanService planService;
    @Resource
    private ZjxdPlanSchemeService schemeService;
    @Resource
    private ZjxdCehuaSchemeService cehuaSchemeService;
    @Resource
    private InstructPreviewService previewService;

    @Override
    @Transactional
    public void savePlan(PlanRequest request) {
        log.info("入参为：{}", JSON.toJSONString(request));
        ZjxdPlan plan = new ZjxdPlan();
        BeanUtils.copyProperties(request, plan);

        String assId = request.getAssId();
        ZjxdPlan zjxdPlan = planService.getOne(Wrappers.<ZjxdPlan>lambdaQuery().eq(ZjxdPlan::getAssId, assId));
        if (zjxdPlan != null) {
            throw new RuntimeException("一个任务对应一个筹划 不可重复【暂时！】");
        }
        plan.setAssId(Long.parseLong(assId));
        plan.setCreateTime(new Date());
        plan.setPlanStatus(AuditEnums.CHOUHUAZ.name());
        plan.setUpdateTime(new Date());
        planService.save(plan);
        assignmentService.update(Wrappers.<ZjxdAssignment>lambdaUpdate().set(ZjxdAssignment::getAssignStatus, AuditEnums.CHOUHUAZ.name()).eq(ZjxdAssignment::getId, assId));
        //todo 入参还缺少一步 入参还应该携带任务信息 发送给筹划平台
    }

    @Override
    public Result getPlanInfo(String id, String status) {
        log.info("getPlanInfo接口入参的ID：{}, 查看阶段是：{}", JSON.toJSONString(id), JSON.toJSONString(status));
        ZjxdPlan zjxdPlan = planService.getOne(Wrappers.<ZjxdPlan>lambdaQuery().eq(ZjxdPlan::getAssId, id));
        //第一次进来 data为null 前段默认进入创建中页面
        if (zjxdPlan == null) {
            return Result.ok();
        }
        //创建中 回显ZJXD_PLAN表内容
        if (status.equals(AuditEnums.CJZ.name())) {
            return Result.ok(zjxdPlan);
        }
        PlanSchemeResponse response = new PlanSchemeResponse();
        //筹划中 回显ZJXD_PLAN_SCHEME表内容
        if (status.equals(AuditEnums.CHOUHUAZ.name())) {
            Long planId = zjxdPlan.getId();
            response.setPlanId(String.valueOf(planId));
            response.setPlanName(zjxdPlan.getPlanName());
            response.setPlanStatus(zjxdPlan.getPlanStatus());
            List<ZjxdPlanScheme> schemeList = schemeService.list(Wrappers.<ZjxdPlanScheme>lambdaQuery().eq(ZjxdPlanScheme::getPlanId, planId));
            if (CollectionUtils.isEmpty(schemeList)) {
                return Result.ok(response);
            }
            List<SchemeResponse> schemeResponseList = new ArrayList<>();
            for (ZjxdPlanScheme zjxdPlanScheme : schemeList) {
                SchemeResponse schemeResponse = new SchemeResponse();
                BeanUtils.copyProperties(zjxdPlanScheme, schemeResponse);
                schemeResponse.setSchemeId(String.valueOf(zjxdPlanScheme.getId()));
                String subDw = zjxdPlanScheme.getSubDw();
                PlanDwEnums planDwEnums = PlanDwEnums.valueOf(subDw);
                schemeResponse.setSubDw(planDwEnums.getDesc());
                schemeResponseList.add(schemeResponse);
                setPreview(schemeResponse, zjxdPlanScheme.getId());
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            schemeResponseList.sort((u1, u2) -> {
                try {
                    Date date1 = dateFormat.parse(u1.getSubTime());
                    Date date2 = dateFormat.parse(u2.getSubTime());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    log.info("转换时间异常：{}", e.getMessage());
                    return 0;
                }
            });
            SchemeResponse schemeResponse = schemeResponseList.get(schemeResponseList.size() - 1);
            schemeResponse.setButtonStatus(true);
            response.setSchemeList(schemeResponseList);
            return Result.ok(response);
        }

        if (status.equals(AuditEnums.CEHAZ.name())) {
            Long planId = zjxdPlan.getId();
            response.setPlanId(String.valueOf(planId));
            response.setPlanName(zjxdPlan.getPlanName());
            response.setPlanStatus(zjxdPlan.getPlanStatus());
            List<ZjxdCehuaScheme> cehuaSchemeList = cehuaSchemeService.list(Wrappers.<ZjxdCehuaScheme>lambdaQuery().eq(ZjxdCehuaScheme::getPlanId, planId));
            if (CollectionUtils.isEmpty(cehuaSchemeList)) {
                return Result.ok(response);
            }
            List<SchemeResponse> chResponseList = new ArrayList<>();
            for (ZjxdCehuaScheme cehuaScheme : cehuaSchemeList) {
                SchemeResponse schemeResponse = new SchemeResponse();
                BeanUtils.copyProperties(cehuaScheme, schemeResponse);
                Long cehuaSchemeId = cehuaScheme.getId();
                schemeResponse.setSchemeId(String.valueOf(cehuaSchemeId));
                String subDw = cehuaScheme.getSubDw();
                PlanDwEnums planDwEnums = PlanDwEnums.valueOf(subDw);
                schemeResponse.setSubDw(planDwEnums.getDesc());
                chResponseList.add(schemeResponse);
                setPreview(schemeResponse, cehuaScheme.getId());
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            chResponseList.sort((u1, u2) -> {
                try {
                    Date date1 = dateFormat.parse(u1.getSubTime());
                    Date date2 = dateFormat.parse(u2.getSubTime());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    log.info("转换时间异常：{}", e.getMessage());
                    return 0;
                }
            });
            SchemeResponse schemeResponse = chResponseList.get(chResponseList.size() - 1);
            schemeResponse.setButtonStatus(true);
            response.setSchemeList(chResponseList);
            return Result.ok(response);
        }

        if (status.equals(AuditEnums.FBZ.name())) {
            Long planId = zjxdPlan.getId();
            List<ZjxdCehuaScheme> cehuaSchemeList = cehuaSchemeService.list(Wrappers.<ZjxdCehuaScheme>lambdaQuery().eq(ZjxdCehuaScheme::getPlanId, planId));

            ZjxdCehuaScheme cehuaScheme = cehuaSchemeList.stream().filter(cehua -> cehua.getSubStatus().equals(SubStatusEnums.TG.name())).findFirst().get();
            return Result.ok(cehuaScheme);
        }
        return Result.ok();
    }

    private void setPreview(SchemeResponse schemeResponse, Long id) {
        List<InstructPreview> previewList = previewService.list(Wrappers
                .<InstructPreview>lambdaQuery().eq(InstructPreview::getTableId, id));
        if (CollectionUtils.isEmpty(previewList)){
            throw new RuntimeException("作战指令尚未生成 请耐心等待");
        }
        List<InstructPreviewRsp> rsps = Lists.newArrayList();
        previewList.forEach(info -> {
            InstructPreviewRsp rsp = new InstructPreviewRsp();
            BeanUtils.copyProperties(info,rsp);
            rsps.add(rsp);
        });
        schemeResponse.setInstructPreviewRsp(rsps);
    }


    @Override
    @Transactional
    public void returnOrPassButton(StageInfoRequest request) {
        String id = request.getId();
        AuditEnums enums = AuditEnums.valueOf(request.getStatus());
        switch (enums) {
            // 筹划中
            case CHOUHUAZ:
                if (request.getType().equals(SubStatusEnums.JJ.name())) {
                    updateSql(request);
                } else {
                    //如果通过了 更改筹划表的任务状态 和通过状态 和审核意见等 同时更改任务表的任务状态为下一阶段 然后策划表新增
//                    ZjxdCehuaScheme cehuaScheme = new ZjxdCehuaScheme();
                    ZjxdPlanScheme planScheme = schemeService.getById(id);
//                    BeanUtils.copyProperties(planScheme, cehuaScheme);
                    updateSql(request);
                    Long planId = planScheme.getPlanId();
                    planService.update(Wrappers.<ZjxdPlan>lambdaUpdate()
                            .set(ZjxdPlan::getPlanStatus, AuditEnums.CEHAZ.name()).eq(ZjxdPlan::getId, planId));
                    //todo 目前是一对一 可以使用getOne
                    ZjxdPlan zjxdPlan = planService.getOne(Wrappers.<ZjxdPlan>lambdaQuery().eq(ZjxdPlan::getId, planId));
                    assignmentService.update(Wrappers.<ZjxdAssignment>lambdaUpdate()
                            .set(ZjxdAssignment::getAssignStatus, AuditEnums.CEHAZ.name()).eq(ZjxdAssignment::getId, zjxdPlan.getAssId()));
//                    cehuaScheme.setSubStatus(SubStatusEnums.DSH.name());
//                    cehuaSchemeService.save(cehuaScheme);
                }

                break;
            case CEHAZ:
                if (request.getType().equals(SubStatusEnums.JJ.name())) {
                    updateChSql(request);
                } else {
                    updateChSql(request);
                    Long planId = cehuaSchemeService.getById(id).getPlanId();
                    planService.update(Wrappers.<ZjxdPlan>lambdaUpdate().set(ZjxdPlan::getPlanStatus, AuditEnums.FBZ.name()).eq(ZjxdPlan::getId, planId));
                    //todo 目前是一对一 可以使用getOne
                    ZjxdPlan zjxdPlan = planService.getOne(Wrappers.<ZjxdPlan>lambdaQuery().eq(ZjxdPlan::getId, planId));
                    assignmentService.update(Wrappers.<ZjxdAssignment>lambdaUpdate()
                            .set(ZjxdAssignment::getAssignStatus, AuditEnums.FBZ.name())
                            .eq(ZjxdAssignment::getId, zjxdPlan.getAssId()));
                }
                break;
        }
    }

    public void updateSql(StageInfoRequest request) {
        schemeService.update(Wrappers.<ZjxdPlanScheme>lambdaUpdate()
                .set(ZjxdPlanScheme::getSubStatus, request.getType())
                .set(ZjxdPlanScheme::getAuditDw, request.getAuditDw())
                .set(ZjxdPlanScheme::getAuditTime, request.getAuditTime())
                .set(ZjxdPlanScheme::getStatusValue, request.getStatusValue())
                .eq(ZjxdPlanScheme::getId, request.getId()));
    }

    public void updateChSql(StageInfoRequest request) {
        cehuaSchemeService.update(Wrappers.<ZjxdCehuaScheme>lambdaUpdate()
                .set(ZjxdCehuaScheme::getSubStatus, request.getType())
                .set(ZjxdCehuaScheme::getAuditDw, request.getAuditDw())
                .set(ZjxdCehuaScheme::getAuditTime, request.getAuditTime())
                .set(ZjxdCehuaScheme::getStatusValue, request.getStatusValue())
                .eq(ZjxdCehuaScheme::getId, request.getId()));
    }
}
